package server.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

public class CooKieUtil {

//    public static String CooKieVal = null;

    public final static String CooKieName = "CookieKey";

    public final static int maxAge = 60*60*48;//48小时过期

    public static String generateUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static String getCooKieVal(HttpServletRequest request) {
        Cookie[] cookies =  request.getCookies();
        if(cookies != null){
            for(Cookie cookie : cookies){
                if(cookie.getName().equals(CooKieName)){
                    return cookie.getValue();
                }
            }
        }
        return  null;
    }
    public static void setCooKieVal(HttpServletResponse response) {
        Cookie cookie = new Cookie(CooKieName, CooKieUtil.generateUUID());
        cookie.setPath("/");
        //cookie.setMaxAge(maxAge);//设置48小时过期
        response.addCookie(cookie);
    }
    //刷新过期时间
    public static void refreshCookieVal(HttpServletResponse response,String val){
        Cookie cookie = new Cookie(CooKieName, val);
        cookie.setPath("/");
        //cookie.setMaxAge(maxAge);//设置48小时过期
        response.addCookie(cookie);
    }
    public static void removeCooKieVal(HttpServletResponse response) {
        Cookie cookie = new Cookie(CooKieName, null);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }
    public static void main(String[] args) {
        System.out.println(CooKieUtil.generateUUID());
    }
}
